package com.jzmy.cultivate.controller;



import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.example.commons.entity.*;
import com.example.commons.utils.*;
import com.jzmy.cultivate.entity.*;


import com.jzmy.cultivate.entity.vo.ConsultationsVo;
import com.jzmy.cultivate.entity.vo.CoursesAndTeacherVo;
import com.jzmy.cultivate.entity.vo.CoursesListVo;
import com.jzmy.cultivate.entity.vo.MyCourseListVo;
import com.jzmy.cultivate.feign.DictOpenFeign;
import com.jzmy.cultivate.feign.ExpertsOpenFeign;
import com.jzmy.cultivate.feign.UserOpenfeign;
import com.jzmy.cultivate.service.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.java.Log;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;


import java.util.*;

/**
 * 资料
 * @author mengzhichao
 * @create 2022-08-25-9:26
 */
@Slf4j
@RestController
@RequestMapping("/data")
public class ApiIndexController {



    @Autowired
    private OrderService orderService;

    @Autowired
    private ConsultationsService consultationsService;

    @Autowired
    private CoursesService coursesService;

    @Autowired
    private CoustuQuestionsAnswersService coustuQuestionsAnswersService;

    @Autowired
    private ChapterService chapterService;

    @Autowired
    private ChapterItemBankService chapterItemBankService;

    @Autowired
    private TrainingResourcesService trainingResourcesService;

    @Autowired
    private UserOpenfeign userOpenfeign;

    @Autowired
    private ExpertsOpenFeign expertsOpenFeign;

    @Autowired
    private TrainingResultsService trainingResultsService;

    @Autowired
    private CourseLearnsService courseLearnsService;

    @Autowired
    private DictOpenFeign dictOpenFeign;

    @Autowired
    private DiscussService discussService;

    @Autowired
    private CoursesUserRelationService coursesUserRelationService;

    /**
     * api小程序端-资料文库查询接口--公开方法，不需要登录
     * @Description: 证书信息列表查询，参数：页码，显示数，栏目名称（筛选条件）
     */
    @GetMapping("/selNewsList")
    @Transactional
    public ApiResult<?> selNewsList(String current, String number, String firstColumn, String columnName,String title) {
        Page<ConsultationsVo> page = consultationsService.selectListPage(Integer.parseInt(current), Integer.parseInt(number),firstColumn, newParameter(columnName),title);
        List<ConsultationsVo> records = page.getRecords();
        List<ConsultationsVo> consultationsVos = new ArrayList<>();
        for (int i=0;i<records.size();i++){
            records.get(i).setFileType(lastName(records.get(i).getFiles()));
            if (records.get(i).getSecondColumn().equals("培训大纲") || records.get(i).getSecondColumn().equals("托育机构从业人员培训大纲")
                    || records.get(i).getSecondColumn().equals("配套资源")|| records.get(i).getSecondColumn().equals("考评配套资源")
                    || records.get(i).getSecondColumn().equals("课证融通")|| records.get(i).getSecondColumn().equals("课证融通标准")
                    || records.get(i).getSecondColumn().equals("技能标准")|| records.get(i).getSecondColumn().equals("职业技能等级标准")
                    || records.get(i).getSecondColumn().equals("操作手册")){
                consultationsVos.add(records.get(i));
            }
        }
        page.setRecords(consultationsVos);
        return ApiResult.success(page);
    }


    public String lastName(String file){
        if (file==null){
            return null;
        }
        if(file.lastIndexOf(".")==-1){
            return "";//文件没有后缀名的情况
        }
        return file.substring(file.lastIndexOf(".")+1);
    }



    /**
     * 参数格式化方法
     * @return
     */
    private String newParameter(String title){
        if ("培训大纲".equals(title)){
            return "托育机构从业人员培训大纲";
        }
        if ("配套资源".equals(title)){
            return "考评配套资源";
        }
        if ("课证融通".equals(title)){
            return "课证融通标准";
        }
        if ("技能标准".equals(title)){
            return "职业技能等级标准";
        }
        return title;
    }

    /**
     *用户是否有访问课程权限
     */
    @GetMapping("/courseUserIs")
    public ApiResult<?>  courseUserIs(Long id) {
        QueryWrapper<JzUserCoursesRelationshipsDO> queryWrapper = new QueryWrapper<>();

        queryWrapper.eq("user_id",JWTUtil.getUser().getId());
        queryWrapper.eq("courses_id",id);
      List list=  coursesUserRelationService.list(queryWrapper);
            if(list.size()>0){
                return ApiResult.success(true);
            }
        return ApiResult.success(false);
    }

    /**
     * api小程序端-课程列表接口--公开方法，不需要登录
     *
     * @Description: 课程列表接口（需分页），参数：页码，显示数，课程名称（筛选条件），证书概况id（筛选条件）排序字段
     * @Param: [current, number, name, profileId]
     */
    @GetMapping("/selCourseList")
    @Transactional
    public ApiResult<?>  selCourseList(String current, String number, String name, String profileId,String newType,String sort) {
        Map map = new HashMap();
        if (StringUtils.isNotBlank(sort)) {
            map.put("sort", sort);
        }else {
            map.put("sort", "default");
        }
        if (StringUtils.isNotBlank(name)) {
            map.put("name", name);
        }
        if (StringUtils.isNotBlank(profileId)) {
            map.put("profileId", Long.parseLong(profileId));
        }
        if (StringUtils.isNotBlank(newType)) {
            map.put("newType", newType);
        }
        Page<CoursesListVo> page = coursesService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        return ApiResult.success(page);
    }




    /**
     * api小程序端-课程详情接口--公开方法，不需要登录
     *
     * @Description: 获取课程详细信息，参数：课程id
     */
    @GetMapping("/selCourseDetails")
    @Transactional
    public ApiResult<?> selCourseDetails(String id) {
        if (StringUtils.isNotBlank(id)) {
            CoursesAndTeacherVo coursesAndTeacherVo = coursesService.selCourseDetail(Long.parseLong(id));
            return ApiResult.success(coursesAndTeacherVo);
        } else {
            return ApiResult.build(ApiEnumError.formatFail.getCode(), "参数为空或格式错误");
        }
    }


    /***
     *  api小程序端—课程问答列表分页查询接口
     *  courseId 课程id
     */
    @GetMapping("/selCoustuQueAns")
    @Transactional
    public ApiResult<?>  selCoustuQueAns(String current, String number, String courseId) {
        if (StringUtils.isBlank(courseId)) {
            return ApiResult.lack("");//缺少参数
        }
        Map map = new HashMap();
        map.put("courseId", courseId);
        Page<CoustuQuestionsAnswers> page = coustuQuestionsAnswersService.selectListPage(Integer.parseInt(current), Integer.parseInt(number), map);
        for (int i = 0; i < page.getRecords().size(); i++) { //添加用户头像
            UserDO twUser = userOpenfeign.getUserById(page.getRecords().get(i).getUserId());
            page.getRecords().get(i).setHeadPortrait(twUser.getHeadPortrait());
        }
        List list = new ArrayList();
        for (int i = 0; i < page.getRecords().size(); i++) {
            CoustuQuestionsAnswers obj = (CoustuQuestionsAnswers) page.getRecords().get(i);
            if (obj.getState() != null) {
                CoustuQuestionsAnswers coustuQuestionsAnswers = coustuQuestionsAnswersService.findOneByKv("pid", obj.getId());
                if (coustuQuestionsAnswers != null) {
                    UserDO userDo = userOpenfeign.getUserById(coustuQuestionsAnswers.getUserId());
                    if (userDo != null) {
                        obj.setTeaUserName(userDo.getName());
                        obj.setUpdateDate(coustuQuestionsAnswers.getCreaterDate()); //修改时间作为回复时间。
                    }
                    obj.setAnswers(coustuQuestionsAnswers.getContents());
                }
            }
            if (obj.getUserId() != null) {
                UserDO userDO = userOpenfeign.getUserById(obj.getUserId());
                if (userDO != null) {
                    if (ValidUtils.isMobile(userDO.getUsername())){
                        String userName = "";
                        String substring1 = userDO.getUsername().substring(0, 3);
                        String substring2 = userDO.getUsername().substring(8, 11);
                        userName = substring1 + "*****" + substring2;
                        obj.setUserName(userName);
                    }else {
                        String userName = userDO.getUsername().substring(0, 1);
                        userName = userName + "**";
                        obj.setUserName(userName);
                    }
                }
            }
            list.add(obj);
        }
        page.setRecords(list);
        return ApiResult.success(page);
    }



    /***
     * api小程序端-课程章节目录列表接口
     * @param id 课程id
     * @return
     */
    @GetMapping("/selChapterList")
    @Transactional
    public ApiResult<?>  selChapterList(String id) {
        List<Map> mapList = new ArrayList<>();
        if (StringUtils.isNotBlank(id)) {
            List<Chapter> chapters = chapterService.findByKv("courses_id", Long.parseLong(id), "is_root", 1);
            if (chapters != null && chapters.size() > 0) {
                for (Chapter chapter : chapters) {
                    Map map1 = new HashMap();
                    map1.put("id", chapter.getId());
                    List<ChapterItemBank> chapterItemBanks = chapterItemBankService.findByKv("chapter_id", chapter.getId(), "type", 0);
                    if (chapterItemBanks != null && chapterItemBanks.size() > 0) {
                        map1.put("isChaItem", "true");
                    } else {
                        map1.put("isChaItem", "false");
                    }
                    if (chapter.getName() != null) {
                        map1.put("name", chapter.getName());
                    } else {
                        map1.put("name", "");
                    }
                    map1.put("isFree", chapter.getIsFree());//是否免费

                    map1.put("level", chapter.getLevel());//层级

                    List<TrainingResources> trainingResources = trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapter.getId());//,"type",1
                    if (trainingResources != null && trainingResources.size() > 0) {
                        int i = 0;
                        for (TrainingResources r : trainingResources) {
                            r.setRindex(i);
                            i++;
                        }
                    }
                    map1.put("resources", trainingResources);
                    if (trainingResources.size() > 0) {
                        map1.put("isHaveResources", 1);
                    } else {
                        map1.put("isHaveResources", 0);
                    }

                    List<Map> map1Children = new ArrayList<>();
                    List<Chapter> chapters2 = chapterService.findByKv("courses_id", Long.parseLong(id), "parent_id", chapter.getId());
                    if (chapters2 != null && chapters2.size() > 0) {
                        for (Chapter chapter2 : chapters2) {
                            Map map2 = new HashMap();
                            map2.put("id", chapter2.getId());
                            List<ChapterItemBank> chapterItemBanks2 = chapterItemBankService.findByKv("chapter_id", chapter2.getId(), "type", 0);
                            if (chapterItemBanks2 != null && chapterItemBanks2.size() > 0) {
                                map2.put("isChaItem", "true");
                            } else {
                                map2.put("isChaItem", "false");
                            }
                            if (chapter2.getName() != null) {
                                map2.put("name", chapter2.getName());
                            } else {
                                map2.put("name", "");
                            }
                            map2.put("isFree", chapter2.getIsFree());//是否免费

                            map2.put("level", chapter2.getLevel());//层级

                            List<TrainingResources> trainingResourcesDOS2 = trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapter2.getId());//,"type",1
                            if (trainingResourcesDOS2 != null && trainingResourcesDOS2.size() > 0) {
                                int i = 0;
                                for (TrainingResources r : trainingResourcesDOS2) {
                                    r.setRindex(i);
                                    i++;
                                }
                            }
                            map2.put("resources", trainingResourcesDOS2);
                            if (trainingResourcesDOS2.size() > 0) {
                                map2.put("isHaveResources", 1);
                            } else {
                                map2.put("isHaveResources", 0);
                            }

                            List<Map> map2Children = new ArrayList<>();
                            List<Chapter> chapters3 = chapterService.findByKv("courses_id", Long.parseLong(id), "parent_id", chapter2.getId());
                            if (chapters3 != null && chapters3.size() > 0) {
                                for (Chapter chapter3 : chapters3) {
                                    System.out.println("id:" + chapter3.getId() + " -- name:" + chapter3.getName());
                                    Map map3 = new HashMap();
                                    map3.put("id", chapter3.getId());
                                    List<ChapterItemBank> chapterItemBankDOS3 = chapterItemBankService.findByKv("chapter_id", chapter3.getId(), "type", 0);
                                    if (chapterItemBankDOS3 != null && chapterItemBankDOS3.size() > 0) {
                                        map3.put("isChaItem", "true");
                                    } else {
                                        map3.put("isChaItem", "false");
                                    }
                                    if (chapter3.getName() != null) {
                                        map3.put("name", chapter3.getName());
                                    } else {
                                        map3.put("name", "");
                                    }
                                    map3.put("isFree", chapter3.getIsFree());//是否免费

                                    map3.put("level", chapter3.getLevel());//层级

                                    List<TrainingResources> trainingResourcesDOS3 = trainingResourcesService.findByKv("courses_id", Long.parseLong(id), "chapter_id", chapter3.getId());//,"type",1
                                    if (trainingResourcesDOS3 != null && trainingResourcesDOS3.size() > 0) {
                                        int i = 0;
                                        for (TrainingResources r : trainingResourcesDOS3) {
                                            r.setRindex(i);
                                            i++;
                                        }
                                    }
                                    map3.put("resources", trainingResourcesDOS3);

                                    if (trainingResourcesDOS3.size() > 0) {
                                        map3.put("isHaveResources", 1);
                                    } else {
                                        map3.put("isHaveResources", 0);
                                    }
                                    map2Children.add(map3);
                                }
                                map2.put("isHaveChildren", 1);
                                map2.put("children", map2Children);
                            } else {
                                map2.put("isHaveChildren", 0);
                                map2.put("children", "");
                            }
                            map1Children.add(map2);
                        }
                        map1.put("isHaveChildren", 1);
                        map1.put("children", map1Children);
                    } else {
                        map1.put("isHaveChildren", 0);
                        map1.put("children", "");
                    }
                    mapList.add(map1);
                }
            }
        }
        return ApiResult.success(mapList);
    }



    /**
     * 新增评论
     */
    @PostMapping("/addComment")
    public ApiResult<?> addComment(String message, String isAnonymous, String pid, String rootId, String courseId) {
        //1.根据token获取用户登录数据
        UserDO user = JWTUtil.getUser();
//        UserDO user =new UserDO();
//        user.setId(1509349086594027522L);
        if (null == user) {
            return ApiResult.invalid();
        }
        if (courseId == null || courseId.equals("")) {
            return ApiResult.fail("当前课程不存在！");
        } else {
            Courses courses = this.coursesService.getById(Long.valueOf(courseId));
            if (courses == null) {
                return ApiResult.fail("当前课程不存在！");
            }
        }
        if (message != null) {
            QueryWrapper wrapper =new QueryWrapper();
            wrapper.orderBy(false,false,"add_time");
            wrapper.eq("user_id", user.getId());

            //当天评论数
            int comment_day_num = 100;

            //评论单位时间(分钟)
            int comment_unit_time = 0;
            DictDO dictDO = (DictDO) dictOpenFeign.findOneByKv("type", "comment_unit_time");
            if (dictDO != null && dictDO.getValue() != null && !dictDO.getValue().equals("")) {
                comment_unit_time = Integer.valueOf(dictDO.getValue());
            }

            //评论数量
            int comment_unit_num = 0;
            DictDO dictDO2 = (DictDO) dictOpenFeign.findOneByKv("type", "comment_unit_num");
            if (dictDO2 != null && dictDO2.getValue() != null && !dictDO2.getValue().equals("")) {
                comment_unit_num = Integer.valueOf(dictDO2.getValue());
            }

            Date newDate = new Date();
            if (comment_unit_time != 0 && comment_unit_num != 0) {
                Calendar date = this.getTimeForSub(
                        0,
                        0,
                        Integer.valueOf(comment_unit_time),
                        0,
                        newDate
                );
                wrapper.between("add_time", date.getTime(), newDate);
                System.out.println("comment_unit_time:" + comment_unit_time);
                System.out.println("comment_unit_num:" + comment_unit_num);
                System.out.println("date:" + date.getTime());
                System.out.println("newDate:" + newDate);
                List<DiscussDO> discussDOS = discussService.list(wrapper);
                if (discussDOS.size() >= comment_unit_num) {
                    return ApiResult.fail("评论过于频繁，请稍候再试！");
                }
            }

            if (comment_day_num != 0) {
                wrapper.between("add_time",getStartTime(),getEndTime());
                System.out.println("----------------------------------------------getStartTime" + getStartTime());
                System.out.println("----------------------------------------------getEndTime" + getEndTime());

                List<DiscussDO> discussDOS = discussService.list(wrapper);
                if (discussDOS.size() >= comment_day_num) {
                        return ApiResult.fail("今日评论过于频繁，请稍候再试！");
                }
            }

            //关键字过虑
            String newMessage = message;
            String comment_keyword = "";
            DictDO dictDO3 = (DictDO) dictOpenFeign.findOneByKv("type", "comment_keyword");
            if (dictDO3 != null && dictDO3.getValue() != null && !dictDO3.getValue().equals("")) {
                comment_keyword = dictDO3.getValue();
                if (comment_keyword != null && !comment_keyword.equals("")) {
                    String[] keywordList = comment_keyword.split(";");
                    if (keywordList.length > 0) {
                        for (int a = 0; a < keywordList.length; a++) {
                            if (newMessage != null && newMessage.contains(keywordList[a])) {
                                newMessage = newMessage.replace(keywordList[a], "***");
                                System.out.println("newMessage:" + a + " " + newMessage);
                            }
                        }
                    }
                }
            }
            System.out.println("newMessage:" + newMessage);

            DiscussDO discussDO = new DiscussDO();
            discussDO.setContent(newMessage);
            if (isAnonymous != null) {
                discussDO.setIsAnonymous(Integer.valueOf(isAnonymous));
            } else {
                discussDO.setIsAnonymous(0);
            }
            if (!pid.equals("-1") && !pid.equals("")) {
                DiscussDO parent = this.discussService.getById(Long.valueOf(pid));
                discussDO.setFromUserId(parent.getUserId());
                discussDO.setPid(Long.valueOf(pid));
            } else {
                if (!rootId.equals("-1") && !rootId.equals("")) {
                    DiscussDO parent = this.discussService.getById(Long.valueOf(rootId));
                    discussDO.setFromUserId(parent.getUserId());
                }
            }
            if (!rootId.equals("-1") && !rootId.equals("")) {
                discussDO.setRootId(Long.valueOf(rootId));
            }

            discussDO.setIsDelete(0);
            discussDO.setAddTime(newDate);
            discussDO.setUserId(user.getId());
            discussDO.setCoursesId(Long.valueOf(courseId));

            if (this.discussService.save(discussDO)) {
                return ApiResult.success(1);
            } else {
                return ApiResult.fail("添加评论失败，数据库错误！");
            }
        } else {
            return ApiResult.fail("请输入评论内容！");
        }
    }


    /**
     * 课程提问接口 ，课程id  提问内容
     * @param courseId
     * @param questions
     * @return
     */
    @PostMapping("/addQuestions")
    @Transactional
    public ApiResult<?> addQuestions(String courseId, String questions) {
        //1.根据token获取用户登录数据
        UserDO user = JWTUtil.getUser();
//        UserDO user =new UserDO();
//        user.setId(1509349086594027522L);
        if (null == user) {
            return ApiResult.invalid();
        }

        if (StringUtils.isBlank(courseId)) {
            return ApiResult.lack("");//缺少参数
        }
        if (StringUtils.isBlank(questions)) {
            return ApiResult.lack("");//缺少参数
        }

        CoustuQuestionsAnswers coustuQuestionsAnswersDO = new CoustuQuestionsAnswers();
        coustuQuestionsAnswersDO.setState(0);//默认未回答
        coustuQuestionsAnswersDO.setCoursesId(Long.parseLong(courseId));//课程id
        coustuQuestionsAnswersDO.setUserId(user.getId());//学生id
        coustuQuestionsAnswersDO.setContents(questions);//问题
        coustuQuestionsAnswersDO.setPid(0L);//默认为0，最高级

        boolean cc = coustuQuestionsAnswersService.save(coustuQuestionsAnswersDO);
        return cc ? ApiResult.success() : ApiResult.fail("提问错误，请稍后重试！");
    }




    //把 一个时间 减去天，时，分，秒
    public Calendar getTimeForSub(int day, int hour, int minute, int second, Date date) {
        Calendar nowTime = Calendar.getInstance();
        if (date != null) {
            nowTime.setTime(date);
        } else {
            nowTime.clear();//1970年1月1日 0点0分0秒
        }
        nowTime.add(Calendar.DATE, -day);
        nowTime.add(Calendar.HOUR, -hour);
        nowTime.add(Calendar.MINUTE, -minute);
        nowTime.add(Calendar.SECOND, -second);
        return nowTime;
    }

    private static Date getStartTime() {
        Calendar todayStart = Calendar.getInstance();

        todayStart.set(Calendar.HOUR, 0);

        todayStart.set(Calendar.MINUTE, 0);

        todayStart.set(Calendar.SECOND, 0);

        todayStart.set(Calendar.MILLISECOND, 0);

        return todayStart.getTime();

    }

    private static Date getEndTime() {
        Calendar todayEnd = Calendar.getInstance();

        todayEnd.set(Calendar.HOUR, 23);

        todayEnd.set(Calendar.MINUTE, 59);

        todayEnd.set(Calendar.SECOND, 59);

        todayEnd.set(Calendar.MILLISECOND, 999);

        return todayEnd.getTime();

    }



    /**
     * api小程序端-个人中心—我的课程列表接口
     *
     * @Description: 查询当前用户的课程列表信息；参数：页码，显示数，状态（筛选条件）
     * @Param: [token, current, number, state]
     */
    @GetMapping("/selMyCourseList")
    @RequiresAuthentication
    public ApiResult<?> selMyCourseList(String current, String number, String state) {
        //1.根据token获取用户登录数据
        UserDO user = JWTUtil.getUser();
        if (null == user) {
            return ApiResult.invalid();
        }

        Map map = new HashMap();
        map.put("userId", user.getId());
        map.put("state", state);
        Page<MyCourseListVo> page = orderService.selByStateUserId(Integer.parseInt(current), Integer.parseInt(number), map);
        if (page != null) {
            List list = new ArrayList();
            for (int i = 0; i < page.getRecords().size(); i++) {
                MyCourseListVo obj = (MyCourseListVo) page.getRecords().get(i);
                if (obj.getTeacherName() != null) {
                    ExpertsDO expertsDO = expertsOpenFeign.findOneByKv("user_id", obj.getTeacherName(), "type", 4);
                    if (expertsDO != null) {
                        obj.setTeacherName(expertsDO.getName());
                    } else {
                        obj.setTeacherName("敬请期待");
                    }
                }

                long allSize = 0;//总章节数
                List<Chapter> chapterDOS = chapterService.findByKv("courses_id", obj.getId());
                if (chapterDOS != null && chapterDOS.size() > 0) {
                    allSize = chapterDOS.size();
                }

                //是否进行过测试(0没有，1已测试）
                Map map1 = new HashMap();
                map1.put("coursesId", obj.getId());
                map1.put("userId", user.getId());
                boolean trac = trainingResultsService.selResultsStateList(map1);
                if (trac) {
                    obj.setIsTestScores(1);
                } else {
                    obj.setIsTestScores(0);
                }

                CourseLearns courseLearns = courseLearnsService.findOneByKv("courses_id", obj.getId(), "user_id", user.getId());
                if (courseLearns != null) {
                    long reSize = courseLearns.getCompletionNumber();//完成章节数
                    if (courseLearns.getState() == 0) {
                        obj.setProcess("100%");
                    } else {
                        Courses courses = coursesService.getById(obj.getId());
                        if (courses.getAdoptFactor().equals("所有章节通过")) {
                            if (allSize != 0) {
                                if (reSize * 100 / allSize >= 100) {
                                    obj.setProcess("100%");
                                } else {
                                    obj.setProcess((reSize * 100 / allSize) + "%");
                                }
                            } else {
                                obj.setProcess("0%");
                            }
                        } else if (courses.getAdoptFactor().equals("所有章节通过以及测试达到合格")) {
                            if (allSize != 0) {
                                if (reSize != 0) {
                                    if ((reSize / allSize) * 100 >= 100) {
                                        obj.setProcess("90%");
                                    } else {
                                        obj.setProcess(((reSize * 100 / allSize) * 0.9) + "%");
                                    }
                                } else {
                                    obj.setProcess("0%");
                                }
                            } else {
                                obj.setProcess("0%");
                            }
                        } else {
                            //课程通过条件为：测试通过；那么这里的情况是课程没有通过，那么无论是有没有测试，都是返回百分之0
                            obj.setProcess("0%");
                        }
                    }
                } else {
                    obj.setProcess("0%");
                }


                list.add(obj);
            }
            page.setRecords(list);
        }
        return ApiResult.success(page);
    }




    /**
     * api小程序端-课程订单提交接口
     *
     * @Description: 用户提交课程购买订单；参数：验证token，课程id
     */
    @PostMapping("/selCourseOrder")
    public ApiResult<?> selCourseOrder(String id) {
        //1.根据token获取用户登录数据
        UserDO user = JWTUtil.getUser();
//        UserDO user =new UserDO();
//        user.setId(1509349086594027522L);
        if (null == user) {
            return ApiResult.invalid();
        }
        Courses coursesDO = coursesService.getById(Long.parseLong(id));
        if (coursesDO != null) {
            Order orderDO1 = orderService.findOneByKv("object_id", coursesDO.getId(), "user_id", user.getId());
            if (orderDO1 == null) {
                Order orderDO = new Order();
                orderDO.setType(0);
                orderDO.setObjectId(Long.parseLong(id));//课程id
                orderDO.setUserId(user.getId());//会员id
                orderDO.setName(coursesDO.getName());//课程名
                orderDO.setOrderAmount(coursesDO.getSpecialPrice());//课程实付金额
                if (coursesDO.getSpecialPrice() == 0) {
                    orderDO.setState(0);//如价格为0，则直接设置为已支付
                    orderDO.setPayTime(new Date());//购买时间
                } else {
                    orderDO.setState(1);//默认未付款
                }
                Map map1 = new HashMap();
                map1.put("name", "课程有效期");
                map1.put("type", "effective_times");
                String times = dictOpenFeign.selDicBy(map1);
                //获取课程有效期,如没有，直接默认一年
                if (times != null) {
                    //判断是否为数字,如不是，直接默认一年
                    if (IdCardUtil.isNumeric(times)) {
                        orderDO.setEffectiveTime(Double.parseDouble(times));
                    } else {
                        orderDO.setEffectiveTime(1.0);
                    }
                } else {
                    orderDO.setEffectiveTime(1.0);
                }

                boolean b = orderService.save(orderDO);
                if (b) {
                    Map map = new HashMap();
                    map.put("orderId", orderDO.getId());//课程订单id
                    return ApiResult.success(map);
                } else {
                    return ApiResult.build(ApiEnumError.SUMBITERR.getCode(), ApiEnumError.SUMBITERR.getMsg());
                }
            } else {
                return ApiResult.build(ApiEnumError.ALREADYPAYCOURSE.getCode(), ApiEnumError.ALREADYPAYCOURSE.getMsg());
            }

        } else {
            return ApiResult.build(ApiEnumError.coursesErr.getCode(), ApiEnumError.coursesErr.getMsg());
        }
    }


    /**
     * 讲师列表查询
     * @param id
     * @return
     */
    @GetMapping("/selLecturer")
    public ApiResult<List> selLecturer(String id){
        Map map =new HashMap();
        Courses coursesDO = coursesService.getById(Long.parseLong(id));
        Long userId = coursesDO.getUserId();
        UserDO user = userOpenfeign.getUserById(userId);
        map.put("userId",user.getId());
        map.put("userName",user.getName());
        map.put("userImg",user.getHeadPortrait());
        List list =new ArrayList();
        list.add(map);
        return ApiResult.success(list);
    }


    /**
     * 讲师详情
     * @return
     */
    @GetMapping("/selLecturerParticulars")
    public ApiResult<UserDO> selLecturerParticulars(String userId){
        UserDO user = userOpenfeign.getUserById(Long.parseLong(userId));
        return ApiResult.success(user);
    }

    /**
     * 判断课程权限
     */
    @GetMapping("/courseJurisdiction")
    public ApiResult<?> courseJurisdiction(String id){
        Map rst =new HashMap();
        rst.put("state",0);
        //1.根据token获取用户登录数据
        UserDO user = JWTUtil.getUser();
//        UserDO user =new UserDO();
//        user.setId(1509349086594027522L);
        if (null == user) {
            return ApiResult.invalid();
        }
        Courses coursesDO = coursesService.getById(Long.parseLong(id));
        QueryWrapper queryWrapper =new QueryWrapper();
        queryWrapper.eq("object_id", coursesDO.getId());
        queryWrapper.eq("user_id", user.getId());
        List list = orderService.list(queryWrapper);
        if (list.size()>0){
            rst.put("state",1);
            return ApiResult.success(rst); //1表示有该课程权限，0表示没有
        }
        return ApiResult.success(rst);
    }
}
